package com.qb.video.http

import com.google.gson.GsonBuilder
import com.qb.common.url.Env
import com.qb.baselibrary.basekotlin.converter.StringConverterFactory
import com.qb.baselibrary.basekotlin.network.interceptor.LoggingInterceptor
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


class RetrofitClientVideo {

    companion object {
        fun getInstance() = SingletonHolder.INSTANCE
        private lateinit var retrofit: Retrofit
    }

    private object SingletonHolder {
        val INSTANCE = RetrofitClientVideo()
    }

    init {
        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())

            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(StringConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
//            .baseUrl(Env.url)
            .build()
    }

    private fun getOkHttpClient(): OkHttpClient {
//        val httpCacheDirectory = File(BaseApplication.context?.externalCacheDir, "RespCache")

        return OkHttpClient.Builder()
//                .cache(Cache(httpCacheDirectory, 20 * 1024 * 1024))
                .retryOnConnectionFailure(true)
            .connectTimeout(60*1000, TimeUnit.SECONDS)
            .readTimeout(45L,TimeUnit.SECONDS)
            .writeTimeout(55L, TimeUnit.SECONDS)
            .addNetworkInterceptor(LoggingInterceptor())
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            .build()
    }

    fun <T> create(service: Class<T>?): T =
        retrofit.create(service!!) ?: throw RuntimeException("Api service is null!")
}